<template>
  <div class="app-container">
    <!--Header 头部区域-->
    <Header v-bind:title="msg"></Header>
    <!--循环渲染每一个商品的信息-->
    <Goods v-for="item in goods"
           :key="item.id"
           :id="item.id"
           :title="item.goods_name"
           :pic="item.goods_img"
           :price="item.goods_price"
           :state="item.goods_state"
           :count="item.goods_count"
           @state-change="getNewState">
      <template v-slot:default>
        <Counter :num="item.goods_count" @num-change="getNewNum(item,$event)"></Counter>
      </template>

    </Goods>
    <!--Footer区域-->
    <Footer :isFull="fullState" @full-change="getFullState" :amount="amt" :all="total"></Footer>
  </div>
</template>

<script>
//导入 axios 请求库

import axios from 'axios'

//1.导入需要的组件
import Header from '@/components/Header/Header.vue'
import Goods from '@/components/Goods/Goods.vue'
import Footer from '@/components/Footer/Footer.vue'
import Counter from "@/components/Counter/Counter.vue"
export default {
  data() {
    return {
      msg: '购物车案例',
      //用来存储购物车数据
      goods: []
    }
  },
  computed: {
    //动态计算出全选的状态是true还是false
    fullState() {
      return this.goods.every(item => item.goods_state)
    },
    //已勾选商品的总价格
    amt() {
      return this.goods
          .filter(item => item.goods_state)
          .reduce((total,item) => (total += item.goods_count* item.goods_price),0)
    },
    //已勾选的商品总数量
    total(){
      return this.goods.filter(item => item.goods_state).reduce((t,item) => (t += item.goods_count),0)
    }
  },
  methods: {
    //封装请求列表数据的方法
    async initCartList() {
      //调用axios的get方法，请求列表数据
      const {data:res} = await axios.get('https://www.escook.cn/api/cart')
      //只要请求成功，就将得到的数据存储到data中
      if (res.status === 200) {
        this.goods = res.list
      }
    },
    //接收子组件传递的数据
    getNewState(e) {
      this.goods.some(item => {
        if (item.id === e.id) {
         item.goods_state = e.value
          //终止循环
          return true
        }
      })
    },
    //接收子组件传递的全选状态
    getFullState(val) {
      this.goods.forEach(item => (item.goods_state = val))
    },
    //获取Counter组件发来的最新的数量值
    getNewNum(item,e) {
      item.goods_count = e
    }
  },
  created() {
    //调用请求数据的方法
    this.initCartList()
  },
  //2.注册组件
  components: {
    Header,
    Goods,
    Footer,
    Counter
  }
}
</script>

<style lang="less" scoped>
.app-container {
   padding-top: 5px;
   padding-bottom: 50px;
 }

</style>
